﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WebApi.Helpers;
using WebApi.Model;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CustomBaseDataController : BaseController
    {
        public CustomBaseDataController(ILogger<CustomBaseDataController> logger) : base(logger)
        {
        }

        [HttpPost("Add")]
        public async Task<ReturnModel> Add(CustomBaseData model)
        {
            return await Save(model, true);
        }

        [HttpPost("Update")]
        public async Task<ReturnModel> Update(CustomBaseData model)
        {
            return await Save(model, false);
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model"></param>
        /// <param name="isInsert"></param>
        /// <returns></returns>
        private async Task<ReturnModel> Save(CustomBaseData model, bool isInsert)
        {
            try
            {
                logger.LogDebug($"isInsert={isInsert};" + JsonConvert.SerializeObject(model));
                if (DbHelper.CustomBaseData.IsAny(c => c.BaseDataType == model.BaseDataType && c.Source == model.Source && c.Id != model.Id))
                    return logger.Code_202("数据已存在");
                else if (isInsert)
                    await DbHelper.CustomBaseData.InsertAsync(model);
                else
                    await DbHelper.GetDbConn().Updateable(model).ExecuteCommandAsync();
                LogToDB("CustomBaseData", isInsert ? "新增" : "更新", $"参数：{JsonConvert.SerializeObject(model)}", "成功");
                return new ReturnModel { Count = 1 };
            }
            catch (Exception ex)
            {
                LogToDB("CustomBaseData", isInsert ? "新增" : "更新", $"参数：{JsonConvert.SerializeObject(model)}", "异常", $"{nameof(Save)}-{ex.Message}");
                return logger.ErrorModel(nameof(CustomBaseDataController) + "-" + nameof(Save), ex);
            }
        }

        [HttpGet("GetList")]
        public async Task<ReturnModel> GetList(string dataType)
        {
            logger.LogInformation($"dataType={dataType}");
            try
            {
                var data = await DbHelper.CustomBaseData.GetListAsync(it => it.BaseDataType == dataType);
                return new ReturnModel { Count = data?.Count ?? 0, Data = data };
            }
            catch (Exception ex)
            {
                LogToDB("CustomBaseData", "查询", $"参数：dataType={dataType}", "异常", $"{nameof(GetList)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(ConfigController)}/{nameof(GetList)}", ex);
            }
        }

        /// <summary>
        /// 获取查询下拉框数据
        /// </summary>
        /// <param name="dataType">查询的数据类型(火车皮号、批次、备注、客户类型)，多个以,分割</param>
        /// <returns></returns>
        [HttpPost("SelectList")]
        public async Task<ReturnModel> SelectList([FromQuery] string dataType)
        {
            try
            {
                string[] dataTypes = dataType?.Split(',');
                var list = await DbHelper.CustomBaseData.AsQueryable().Where(it => it.Enable == true && dataTypes.Contains(it.BaseDataType)).Select(it => new { Key = it.BaseDataType, Value = it.Source }).Distinct().ToListAsync();
                return new ReturnModel { Count = list.Count, Data = list };
            }
            catch (Exception ex)
            {
                return logger.ErrorModel($"{nameof(CustomBaseDataController)}/{nameof(SelectList)}", ex);
            }
        }

        /// <summary>
        /// 添加输入时自动填充项
        /// </summary>
        /// <param name="keyValuePairs">[{"Key":"火车皮号","Value":"1"},{"Key":"批次","Value":"2"},{ "Key":"发货单位","Value":"4"}]</param>
        /// <returns></returns>
        [HttpPost("AddHistory")]
        public async Task<ReturnModel> AddHistory(List<KeyValuePair<string,string>> keyValuePairs)
        {
            try
            {
                logger.LogDebug(JsonConvert.SerializeObject(keyValuePairs));
                int count = 0;
                foreach (KeyValuePair<string, string> item in keyValuePairs)
                {
                    switch (item.Key)
                    {
                        case "火车皮号":
                        case "批次":
                        case "备注":
                        case "客户类型":
                            ReturnModel ret= await Add(new CustomBaseData { BaseDataType = item.Key, Source = item.Value });
                            count += ret.Count;
                            break;

                        case "发货单位":
                            if (!DbHelper.SenderList.IsAny(c => c.sender == item.Value))
                                if (await DbHelper.SenderList.InsertAsync(new SenderList { sender = item.Value }))
                                    count++;
                            break;

                        case "收货单位":
                            if (!DbHelper.ReceiverList.IsAny(c => c.receiver == item.Value))
                                if(await DbHelper.ReceiverList.InsertAsync(new ReceiverList { receiver = item.Value }))
                                    count++;
                            break;

                        case "运输单位":
                            if (!DbHelper.TransporterList.IsAny(c => c.transporter == item.Value))
                                if (await DbHelper.TransporterList.InsertAsync(new TransporterList { transporter = item.Value }))
                                    count++;
                            break;

                        case "货物名称":
                            if (!DbHelper.ProductList.IsAny(c => c.product == item.Value))
                                if(await DbHelper.ProductList.InsertAsync(new ProductList { product = item.Value }))
                                    count++;
                            break;
                    }
                }
                LogToDB("History", "新增", $"参数：{JsonConvert.SerializeObject(keyValuePairs)}", "成功");
                return new ReturnModel { Count = count };
            }
            catch (Exception ex)
            {
                LogToDB("History", "新增", $"参数：{JsonConvert.SerializeObject(keyValuePairs)}", "异常", $"History-{ex.Message}");
                return logger.ErrorModel("History", ex);
            }
        }
    }
}